package com.whsxt.controller;

import com.whsxt.common.AjaxResult;
import com.whsxt.domain.Permission;
import com.whsxt.dto.PermissionDto;
import com.whsxt.service.PermissionService;
import com.whsxt.utils.Result2DTreeVoUtils;
import com.whsxt.vo.BaseDtreeVo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/permission")
@RequiresRoles("admin")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/findAll.do")
    public AjaxResult findAll(){
        List<Permission> perms = permissionService.selectAll(null);
        return AjaxResult.ok(perms);
    }

    @RequestMapping("/delete.do")
    public AjaxResult delete(Integer[] id){
        boolean isOk = permissionService.batchRemove(Arrays.asList(id));
        return isOk? AjaxResult.ok() : AjaxResult.error("删除失败");
    }

    @RequestMapping("/loadDirectoryAndMenu.do")
    public AjaxResult loadDirectoryAndMenu(){
        List<Permission> dirAndMenuList = permissionService.selectAll(Arrays.asList(0, 1));
        return AjaxResult.ok(dirAndMenuList);
    }

    @RequestMapping("/add.do")
    public AjaxResult add(PermissionDto permissionDto){
        boolean isOk = permissionService.save(permissionDto);
        return isOk ? AjaxResult.ok(): AjaxResult.error("添加数据出错");
    }

    @RequestMapping("/edit.do")
    public AjaxResult edit(PermissionDto permissionDto){
        boolean isOk = permissionService.update(permissionDto);
        return isOk ? AjaxResult.ok(): AjaxResult.error("添加数据出错");
    }


    /**
     * 加载权限的 dtree 数据
     * @param roleId
     * @return
     */
    @RequestMapping("/loadPermsTree.do")
    public AjaxResult loadPermsTree(Integer roleId){
        // 先查询出所有的权限
        List<Permission> permissions = permissionService.selectAll(null);
        // 在通过角色 id 查询出角色所拥有的权限id，用于回填到权限树中进行展示
        List<Integer> permsIds = permissionService.selectPermsByRoleId(roleId);
        // 在通过工具类转化成前端所需要的视图对象
        List<BaseDtreeVo> permsDtree = Result2DTreeVoUtils.perms2Dtree(permissions, permsIds);
        return AjaxResult.ok(permsDtree);
    }
}
